// 6. Z 字形变换

/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function (s, numRows) {
    let result = "";
    let length = s.length;
    let verticalNumber = numRows;
    let slashNumber = numRows > 2 ? numRows - 1 : 0;
    let verticalArray = [];
    let slashArray = [];
    let slashTime = 1;
    let leftBoundary = verticalNumber * slashTime;
    let rightBoundary = leftBoundary + slashNumber;
    let slashGrouping = numRows > 2 ? numRows - 2 : 0;
    let slashGroup = [];
    let slashIndex = slashGrouping - 1;

    for (let i = 1; i < length + 1; i++) {
        let element = s[i - 1];

        if (i > leftBoundary && i < rightBoundary) {
            slashTime++;
            if (slashTime === slashNumber) {
                slashTime = 1;
                leftBoundary = rightBoundary + slashNumber;
                rightBoundary = leftBoundary + slashNumber;
            }

            slashArray.push(element);
            continue;
        }

        verticalArray.push(element);
    }

    slashArray.forEach((p, index) => {
        let groupIndex = Math.floor(index / slashGrouping);
        if (index % slashGrouping === 0) {
            slashGroup[groupIndex] = [];
        }
        slashGroup[groupIndex].push(p);
    });

    for (let index = 0; index < numRows; index++) {

        for (let m = 0; m < Math.ceil(verticalArray.length / numRows); m++) {
            let element = verticalArray[index + numRows * m];
            if (!!element) {
                result += element;
            }

            if (index !== 0 && index !== numRows - 1) {
                console.log('momo', slashGroup[m], slashIndex, slashGrouping)
                let slashElement = slashGroup[m] ? slashGroup[m][slashIndex] : false;
                if (!!slashElement) {
                    result += slashElement;
                }
            }
        }

        if (index !== 0 && index !== numRows - 1) {
            slashIndex--;
            if (slashIndex < 0) {
                slashIndex = 0;
            }
        }
    }

    console.log("verticalArray: ", verticalArray);
    console.log('slashGroup: ', slashGroup)

    return result;
};

// console.log("reuslt PAHNAPLSIIGYIR", "PAHNAPLSIIGYIR" === convert("PAYPALISHIRING", 3));
console.log("reuslt PINALSIGYAHRPI", convert("PAYPALISHIRING", 2));
